<template>
  <div class="container">
    <!--      题目属性-->
    <div class="container-property">
      <div class="container-property-time"></div>
      <div class="container-property-text">题目属性</div>
    </div>
    <!--    end-->
    <div class="container-form">
      <el-form :model="$store.state.exam.exam.read" :rules="rules" ref="ruleForm" label-width="120px"
               class="demo-ruleForm">
        <div style="display: flex">
          <div>
            <el-form-item label="题目分数" prop="score">
              <el-input-number :min="0.5" :step="0.5" :max="100" clearable
                               v-model="$store.state.exam.exam.read.score"></el-input-number>
            </el-form-item>
          </div>
          <div style="margin-left: 20px">
            <el-form-item label="题目显示名称" prop="show_type">
              <el-input clearable v-model="$store.state.exam.exam.read.show_type"></el-input>
            </el-form-item>
          </div>
        </div>
        <div style="display: flex">
          <div>
            <el-form-item label="题目类型" prop="pattern">
              <el-radio v-model="$store.state.exam.exam.read.pattern" label="作业">阶段测评</el-radio>
              <el-radio v-model="$store.state.exam.exam.read.pattern" label="考试">综合测评</el-radio>
            </el-form-item>
          </div>
          <div style="margin-left: 20px">
            <el-form-item label="试卷/作业名称" prop="paper_name">
              <el-input clearable v-model="$store.state.exam.exam.read.paper_name"></el-input>
            </el-form-item>
          </div>
        </div>
      </el-form>
    </div>
    <!--      题目属性-->
    <div class="container-property">
      <div class="container-property-time"></div>
      <div class="container-property-text">题目（题干内容）</div>
    </div>
    <!--    end-->

    <div class="container-title" id="edite">
      <div style="border: 1px solid #ccc;z-index: 1000">
        <!-- 工具栏 -->
        <Toolbar
          v-if="isEditer"
          style="border-bottom: 1px solid #ccc"
          :editorId="editorId"
          :defaultConfig="toolbarConfig"
        />
        <!-- 编辑器 -->
        <Editor
          v-if="isEditer"
          style="height: 200px"
          :editorId="editorId"
          :defaultConfig="editorConfig"
          @onChange="onChange"
          :defaultHtml="defaultHtml"
        />
      </div>
    </div>

    <div @click="addItem" class="container-addItem">
      <span>+ 添加一个新的子试题</span>
    </div>

    <div class="container-item" style="margin-top: 20px">
      <div>题目名称</div>
      <div>题目类型</div>
      <div>操作</div>
    </div>
    <div class="container-item" v-for="(item,index) in $store.state.exam.readList" :key="index">
      <el-tooltip class="item" effect="dark" placement="top">
        <div slot="content" v-html="item.title"></div>
        <div class="container-item-text" v-html="richTextFormat(item.title)"></div>
      </el-tooltip>
      <div>{{ item.type }}</div>
      <div style="cursor: pointer">
        <el-link @click="edite(index)" type="primary">编辑</el-link>
        <el-popconfirm
          @confirm="delDate(index)"
          confirm-button-text='好的'
          cancel-button-text='不用了'
          icon="el-icon-info"
          icon-color="red"
          title="这是一段内容确定删除吗？"
        >
          <el-link slot="reference" type="danger" style="margin-left: 10px">删除</el-link>
        </el-popconfirm>
      </div>
    </div>
    <!--    弹窗区域-->
    <el-dialog
      title="选择类型"
      :visible.sync="dialogVisible"
      width="30%"
      :modal="false"
    >
      <div style="display: flex;flex-wrap: wrap">
        <div style="margin-left: 50px;margin-top: 30px" v-for="(item,index) in type" :key="index">
          <el-radio style="margin-bottom: 10px" v-model="types" :label="item" size="medium" border>{{ item }}</el-radio>
        </div>
      </div>
      <div style="
      display: flex;
      justify-content: center;
      margin-top: 20px">
        <el-button @click="onConfirm" type="primary">确定</el-button>
        <el-button @click="onCloseDialog" type="info">取消</el-button>
      </div>
    </el-dialog>
    <!--    end-->

    <!--    保存按钮-->
    <div class="container-button">
      <el-row>
        <el-button v-if="$store.state.exam.edit.type == 0 && $store.state.exam.edit.name == ''  " @click="onSubmit"
                   type="primary" round>
          保存/继续添加
        </el-button>
        <el-button v-if="$store.state.exam.edit.type == 0 && $store.state.exam.edit.name != '' " @click="onSubmit"
                   type="primary" round>
          更新/关闭
        </el-button>
        <el-button v-if="$store.state.exam.edit.type == 1 " @click="onSubmit"
                   type="primary" round>
          保存/返回
        </el-button>
        <el-button @click="onClose" type="info" round>{{
            $store.state.exam.edit.type == 0 ? '取消/关闭' : '取消/返回'
          }}
        </el-button>
      </el-row>
    </div>
    <!--    end-->
  </div>
</template>

<script>
let _this;
export default {
  data() {
    return {
      isEditer:false,
      types: '单选题',
      type: ['单选题', '多选题', '判断题', '填空题', '简答题',],
      dialogVisible: false,
      itemJson: [],
      editorId: 'wangEditor-read', // 定义一个编辑器 id ，要求：全局唯一且不变。重要！！！
      latestContent: '', // 用于存储编辑器最新的内容，onChange 时修改
      toolbarConfig: {},
      defaultHtml: '',//内容
      editorConfig: {
        MENU_CONF: {//图片上传配置
          uploadImage: {
            fieldName: 'file',
            server: 'http://www.free.com/api/Upload/upload'
          }
        },
        placeholder: '请输入内容...',
      },
      ruleForm: {
        title: '',
        score: '2',
        pattern: 0,
        paper_name: '',
        show_type: '阅读题',
        answer: '',
      },
      rules: {
        score: [
          {required: true, message: '请输入题目分数', trigger: 'blur'},
        ],
        show_type: [
          {required: true, message: '请输入题目显示类型', trigger: 'blur'},
        ],
        pattern: [
          {required: true, message: '请选择题目类型', trigger: 'blur'},
        ],
        paper_name: [
          {required: true, message: '请输入题目归属名称', trigger: 'blur'},
        ],
      }
    }
  },
  watch: {
    "$store.state.exam.exam.read": {
      handler: function (val) {
        this.isEditer = false;
        setTimeout(() => {
          this.defaultHtml = `<div>${val['title']}</div>`;
          this.isEditer = true;
        },0)
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    edite: function (index) {
      let obj = this.$store.state.exam.readList[index];

      if (obj['type'] == '单选题') {
        this.$store.commit('exam/setDan', obj);
        this.$emit('readSelectType', {types: '单选题'});
      } else if (obj['type'] == '多选题') {
        let duo = {
          answer: obj['answer'] == null ? [] : Array.isArray(obj['answer']) ? obj['answer'] : obj['answer'].split(",")
        }
        this.$store.commit('exam/setDuo', Object.assign(obj, duo));
        this.$emit('readSelectType', {types: '多选题'});
      } else if (obj['type'] == '判断题') {
        this.$store.commit('exam/setPan', obj);
        this.$emit('readSelectType', {types: '判断题'});
      } else if (obj['type'] == '填空题') {
        let tian = {
          answer: obj['answer'] == null ? [] : obj['answer'].split(",")
        }
        this.$store.commit('exam/setTian', Object.assign(obj, tian));
        this.$emit('readSelectType', {types: '填空题'});
      } else if (obj['type'] == '简答题') {
        this.$store.commit('exam/setJieDa', obj);
        this.$emit('readSelectType', {types: '简答题'});
      }
      this.$store.commit('exam/setReadIndex', index);
    },

    /**
     * 删除单条数据
     * @param index
     */
    delDate: function (index) {
      this.$store.commit('exam/delReadList', index);
    },

    //富文本过滤
    richTextFormat(value = '', len = 8) {
      // value = value.replace(/<\/?[^>]*>/g,'')
      value = value.replace(/<\/?.+?>/g, '');
      value = value.replace(/\s+/g, '');
      if (value.length > 30) {
        return value.slice(0, len) + "...";
      }
      return value;
    },

    onConfirm: function () {
      this.dialogVisible = false;
      this.$emit('readSelectType', {types: this.types});
    },
    onCloseDialog: function () {
      this.dialogVisible = false;
    },

    addItem: function () {
      this.dialogVisible = true;
    },

    onChange(editor) {
      //使用 editor.getHtml() 获取 HTML 内容。使用 editor.getText() 获取纯文本内容 使用 editor.children 获取 JSON 内容。
      this.latestContent = editor.getHtml()
    },
    onSubmit: function () {
      if (this.$store.state.exam.readList.length == 0) {
        this.$message.error('请添加一个子试题');
        return;
      }
      if (this.$md(this.editorId).isEmpty()) {
        this.$message.error('请输入题目');
        return;
      }
      if (this.$store.state.exam.exam.read.score == '') {
        this.$message.error('请选择题目的分数');
        return;
      }
      if (this.$store.state.exam.exam.read.show_type == '') {
        this.$message.error('请输入题目显示类型');
        return;
      }
      if (this.$store.state.exam.exam.read.pattern == null) {
        this.$message.error('请选择题目类型');
        return;
      }
      if (this.$store.state.exam.exam.read.paper_name == '') {
        this.$message.error('请输入题目归属名称');
        return;
      }
      let obj = {
        title: _this.latestContent,
        score: _this.$store.state.exam.exam.read['score'],
        paper_name: _this.$store.state.exam.exam.read['paper_name'],
        pattern: _this.$store.state.exam.exam.read['pattern'],
        show_type: _this.$store.state.exam.exam.read['show_type'],
        type: _this.$store.state.exam.exam.read['type'],
        answer: JSON.stringify(_this.$store.state.exam.readList),
      };
      this.$emit('onSubmit', obj);
      this.clearDate();
    },
    onClose: function () {
      this.clearDate();
      this.$emit('onClose');
    },
    clearDate: function () {
      this.ruleForm.answer = '';
      this.ruleForm.title = '';
      this.ruleForm.pattern = this.$store.state.exam.exam.read.pattern;
      this.ruleForm.paper_name = this.$store.state.exam.exam.read.paper_name;
      this.$store.commit('exam/setReadVlaue', this.ruleForm);
      this.$store.commit('exam/setReadListValue', []);
      this.$md(this.editorId).clear();
    },
  },
  created() {
    _this = this;
    this.$store.commit('exam/setRead', {type: 0, name: '阅读题'});
    this.defaultHtml = `<div>${this.$store.state.exam.exam.read['title']}</div>>`;

  }

}
</script>

<style lang="scss">

.container {
  min-height: 500px;

  .container-addItem {
    margin-left: 50px;
    margin-top: 20px;
    padding: 10px;
    background-color: #f2f2f2;
    font-size: 18px;
    font-weight: bold;
    text-align: center;
    color: black;
  }

  .container-item {
    align-items: baseline;
    margin-bottom: 1.5px;
    padding: 10px;
    margin-left: 50px;
    border: 1px solid #f2f2f2;
    display: grid;
    grid-template-columns: repeat(3, 33.33%);
    grid-template-rows: repeat(3, 33.33%);
    text-align: center;
  }

  .container-property {
    width: 300px;
    display: flex;
    align-items: center;

    .container-property-time {
      width: 6px;
      height: 20px;
      background-color: #3a8ee6;
    }

    .container-property-text {
      margin-left: 10px;
      font-weight: bold;
      font-size: 18px;
      color: black;
    }
  }

  .container-form {
    margin-top: 10px;
  }

  .container-title {
    z-index: 1000;
    margin-top: 20px;
    margin-left: 50px;
  }

  .container-select {
    margin-top: 20px;

    .container-select-item {
      font-weight: bold;
      font-size: 20px;
    }
  }

  .container-button {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }
}
</style>
